﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using OfficeHelper.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace OfficeHelper.ViewModel
{
    public class TranslateViewModel: OfficeHelpViewModelBase
    {

        TranslateBaiduRequestObj translateBaiduRequestObj;

        public TranslateViewModel()
        {
            TranslateCommand = new RelayCommand(Translate);
            DeleteEmptyLinesCommand = new RelayCommand(DeleteEmptyLines);
            TranStrClearCommand = new RelayCommand(TranStrClear);
            TranStrCopyCommand = new RelayCommand(TranStrCopy);
            TranStrTestCommand = new RelayCommand(TranStrTest);

            translateBaiduRequestObj = new TranslateBaiduRequestObj()
            {
                appid = MySetting.BaiduTranAppid,
                key = MySetting.BaiduTranKey,
            };
        }

        private void TranStrTest()
        {
            var origin = TranDst;
            if (origin != null && origin.Length > 0)
            {
                string[] splitLine = origin.Split((new string[] { Environment.NewLine }), StringSplitOptions.RemoveEmptyEntries);

                if (splitLine != null)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var item in splitLine)
                    {
                        //select
                        stringBuilder.Append("@" + item + "=" + item+",");
                        //insert1
                        //stringBuilder.Append(item+",");
                        //insert2
                        //stringBuilder.Append("@"+item+",");

                        //update
                        //stringBuilder.Append(item + "=@" + item+",");
                        //stringBuilder.Append(item.TrimEnd());
                        //stringBuilder.AppendLine();
                    }

                    TranDst = stringBuilder.ToString();
                }

            }
        }

        /// <summary>
        /// 全部复制到剪贴板
        /// </summary>
        private void TranStrCopy()
        {
            if (TranDst!=null && TranDst.Length>0)
            {
                Clipboard.SetData(DataFormats.Text,TranDst);
            }
        }

        private void TranStrClear()
        {
            TranDst = "";
        }

        /// <summary>
        /// 删除空行
        /// </summary>
        private void DeleteEmptyLines()
        {
            var origin = TranDst;
            if (origin != null && origin.Length > 0)
            {
                string[] splitLine = origin.Split((new string[] { Environment.NewLine }),                  StringSplitOptions.RemoveEmptyEntries);

                if (splitLine!=null)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (var item in splitLine)
                    {
                        stringBuilder.Append(item.TrimEnd());
                        stringBuilder.AppendLine();
                    }

                    TranDst = stringBuilder.ToString();
                }
                
            }
        }
        /// <summary>
        /// 翻译命令
        /// </summary>
        private void Translate()
        {
            try
            {
                if (String.IsNullOrEmpty(MySetting.BaiduTranKey) || MySetting.BaiduTranAppid == 0)
                {
                    TranslateMyApi();
                }
                else
                {
                    TranslateBaidu();
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox(ex.ToString());
             }
        }

        private void TranslateMyApi()
        {
            if (TranSrc != null && TranSrc.Length > 0)
            {
                WebClient client = new WebClient();
                TranSrc = TranSrc.Replace(@"#", "%23");
                translateBaiduRequestObj.q = TranSrc;
                translateBaiduRequestObj.from = MySetting.SrcLangue;
                translateBaiduRequestObj.to = MySetting.DstLangue;
                string url = translateBaiduRequestObj.GetRequestStrByChenChaoAPI();
                var buffer = client.DownloadData(url);
                string result = Encoding.UTF8.GetString(buffer);

                StringReader sr = new StringReader(result);
                JsonTextReader jsonReader = new JsonTextReader(sr);
                JsonSerializer serializer = new JsonSerializer();
                var r = serializer.Deserialize<TranslateMyAPITObj>(jsonReader);
                if (r.success)
                {
                    String dst = "";
                    foreach (var item in r.result.trans_result)
                    {
                        dst += item.dst + Environment.NewLine;
                    }
                    TranDst = dst;
                }
            }
        }

        /// <summary>
        /// 百度翻译
        /// </summary>
        private void TranslateBaidu() {
            if (TranSrc != null && TranSrc.Length > 0)
            {
                WebClient client = new WebClient();
                TranSrc = TranSrc.Replace(@"#", "%23");
                translateBaiduRequestObj.q = TranSrc;
                translateBaiduRequestObj.from = MySetting.SrcLangue;
                translateBaiduRequestObj.to = MySetting.DstLangue;
                string url = translateBaiduRequestObj.GetRequestStr();
                var buffer = client.DownloadData(url);
                string result = Encoding.UTF8.GetString(buffer);

                StringReader sr = new StringReader(result);
                JsonTextReader jsonReader = new JsonTextReader(sr);
                JsonSerializer serializer = new JsonSerializer();
                var r = serializer.Deserialize<TranslateBaiduResultObj>(jsonReader);

                String dst = "";
                foreach (var item in r.trans_result)
                {
                    dst += item.dst + Environment.NewLine;
                }
                TranDst = dst;
            }
        }

        public ICommand TranslateCommand { get; set; }
        public ICommand DeleteEmptyLinesCommand { get; set; }
        public ICommand TranStrClearCommand { get; set; }
        public ICommand TranStrCopyCommand { get; set; }
        public ICommand TranStrTestCommand { get; set; }

        private string _TranSrc;
        /// <summary>
        /// 源
        /// </summary>
        public string TranSrc
        {
            get { return _TranSrc; }
            set
            {
                Set("TranSrc", ref _TranSrc, value);
                MySetting.Save();
            }
        }

        private string _TranDst;
        /// <summary>
        /// 结果
        /// </summary>
        public string TranDst
        {
            get { return _TranDst; }
            set
            {
                Set("TranDst", ref _TranDst, value);
                MySetting.Save();
            }
        }

        public List<TranslateBaiduLangue> SrcLangues { get; set; } = TranslateBaiduLangue.GetSrcLangues();
        public List<TranslateBaiduLangue> DstLangues { get; set; } = TranslateBaiduLangue.GetDstLangues();

    }
}
